﻿using CSRedis;
using Himp.TaskScheduling.Hangfire.Models;
using Microsoft.AspNetCore.DataProtection.KeyManagement;
using Microsoft.Extensions.Options;
using System.Data;

namespace Himp.TaskScheduling.Hangfire.Workers
{
    public class NotifyWorker: IHostedService
    {
        #region 字段

        private CSRedisClient _client;
        private Timer _timer;
        private readonly TimeSpan _interval = TimeSpan.FromMilliseconds(10000);
        private readonly TimeSpan _delay = TimeSpan.FromMilliseconds(0);
        private bool _isExecuting = false;
        Dictionary<string, object> keyValuePairs = new Dictionary<string, object>();
        private static readonly object _lock = new object();
        private bool _init = false;
        private ILogger<RedisToMqttWorker> _logger;
        private readonly ConnectionStringOption _connectionStrings;

        #endregion

        #region 方法

        public NotifyWorker(ILogger<RedisToMqttWorker> logger
            , IOptions<ConnectionStringOption> connectionStrings)
        {
            _connectionStrings = connectionStrings.Value;
            _logger = logger;
            // 初始化计时器，初始时不启动，等待 StartAsync 启动
            _timer = new Timer(ExecuteJob, null, _delay, Timeout.InfiniteTimeSpan);
            _client = new CSRedis.CSRedisClient(_connectionStrings.KaiYRedis);
            RedisHelper.Initialization(_client);
            _init = true;
        }

        private async void ExecuteJob(object state)
        {
            if (_isExecuting || !_init)
            {
                // 如果任务正在执行，则跳过
                return;
            }

            lock (_lock)
            {
                if (_isExecuting)
                {
                    return;
                }
                _isExecuting = true;
            }

            try
            {
                // 你的任务逻辑
                await RunAsync();

            }
            catch (Exception e)
            {
                await Console.Out.WriteLineAsync(e.Message);
            }
            finally
            {
                GC.Collect(0);
                lock (_lock)
                {
                    _isExecuting = false;
                }
                // 任务完成后重新设置计时器
                _timer.Change(_interval, Timeout.InfiniteTimeSpan);
            }
        }

        private async Task RunAsync()
        {
            if (MqttClientHelper.Connected)
            {
                var aps1Plc1St6mm = await RedisHelper.GetAsync("APS1:PLC1:ST_6mm制样流程:Value");
                var aps1Plc1St3mm = await RedisHelper.GetAsync("APS1:PLC1:ST_3mm制样流程:Value");
                var aps1Plc1St3mm_2 = await RedisHelper.GetAsync("APS1:PLC1:ST_3mm缩分流程:Value");

                if (aps1Plc1St6mm == "0" && aps1Plc1St3mm == "0" && aps1Plc1St3mm_2 == "0")
                {
                    var topicFullPath = "APS1/PLC1";
                    await MqttClientHelper.PublishStringAsync(topicFullPath + "/Alarm", $"制样机可加料");
                }
            }
        }

        public Task StartAsync(CancellationToken cancellationToken)
        {
            _timer.Change(_delay, _interval);
            return Task.CompletedTask;
        }

        public Task StopAsync(CancellationToken cancellationToken)
        {
            _timer?.Dispose();
            return Task.CompletedTask;
        }

        public void Dispose()
        {
            _timer?.Dispose();
        }

        #endregion
    }
}
